#import "JoinClassViewController.h"
#import "MainViewCreater.h"
#import "RequestServerAPI.h"
#import "PopUIManager.h"
#import "JDFTooltipView.h"
#import "Utils.h"
#import "UserDao.h"
#import "JsonUtil.h"
#import "NetWorkManager.h"
#import "MultiBabyViewController.h"
#import "AppDelegate.h"

@interface JoinClassViewController()
@property (weak, nonatomic) IBOutlet UIButton *helpBtn;
@property (strong,nonatomic) JDFTooltipView *tooltip;
@property BOOL toolShow;
@property BOOL start;
@end

@implementation JoinClassViewController
@synthesize schoolCodeInput,joinButton;
- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    self.navigationController.navigationBar.barStyle = UIBarStyleBlack;
    [self customView];
    
}

-(void)customView
{
    joinButton.layer.cornerRadius = 5;
    joinButton.backgroundColor = UIColorMake(252, 74, 74);
    if ([self respondsToSelector:@selector(edgesForExtendedLayout)])
        self.edgesForExtendedLayout = UIRectEdgeNone;
    self.navigationItem.title = @"添加班级";
    UIBarButtonItem *backButton = [[UIBarButtonItem alloc]
                                   initWithTitle:@""
                                   style:UIBarButtonItemStylePlain
                                   target:nil
                                   action:nil];
    
    self.navigationItem.backBarButtonItem=backButton;
    if(_babyid==0){
        self.navigationItem.rightBarButtonItem
        =[[UIBarButtonItem alloc]initWithTitle:@"跳过" style:UIBarButtonItemStylePlain target:self action:@selector(stepOver:)];

    }
       [Utils textFiled:schoolCodeInput padding:15];
    
    _toolShow = NO;
    _start = NO;
    
    [self.navigationController.navigationBar setBarTintColor:UIColorMake(252,74,74)];
    self.navigationController.navigationBar.shadowImage = nil;
    self.navigationController.navigationBar.translucent = NO;

     
}

-(void)clickView:(id)sender
{
    if(_start == NO && _toolShow == YES){
        [_tooltip hideAnimated:YES];
    }
}

- (IBAction)helpTip:(id)sender {
   // [[PopUIManager getInstanse] popAlertView:self title:@"提示" message:@"输入园所号即可加入幼儿园" cancelButtonTitle:@"确定"];
    if(_tooltip == nil){
        _tooltip =[[JDFTooltipView alloc]initWithTargetView:self.helpBtn hostView:self.view tooltipText:@"已开通服务的班级都有一个班级码，不知道班级码？问问老师！" arrowDirection:JDFTooltipViewArrowDirectionUp width:300.00f showCompletionBlock:^{
            _toolShow =YES;
            _start = NO;
        } hideCompletionBlock:^{
            _toolShow =NO;
            _start = NO;
        }];
    }
    if(_start ==NO){
        _start=YES;
    }else{
        return;
    }
    if(_toolShow){
        [_tooltip hideAnimated:YES];
    }else{
        [_tooltip show];
    }
}

- (void)stepOver:(id)sender {
    if(_babyid>0){
        [self.navigationController popToRootViewControllerAnimated:YES];
    }else{
        [self goInMain];
    }
}

-(void)goInMain
{
    UIViewController *mainViewController = [[MainViewCreater getInstance]createMainView];
       UIWindow *window = [[UIApplication sharedApplication]keyWindow];
    window.rootViewController = mainViewController;
}

- (IBAction)joinClass:(id)sender {
    [self.view endEditing:YES];
    NSString* class_code = schoolCodeInput.text;
    if([class_code isEqualToString:@""]||class_code.length==0){
        [[PopUIManager getInstanse]popAlertView:nil title:@"提示" message:@"班级码不能为空~" cancelButtonTitle:@"确定"];
        return;
    }
    NSString* uid = [NSString stringWithFormat:@"%ld",[[UserDao getInstance]getUserId]];
    BabyInfo *baby;
    if(_babyid>0){
        baby = [[BabyDao getInstance]getBabyInfo:_babyid];
    }else{
        baby=[[UserDao getInstance]getCurrentBaby];
    }
    
    NSString *dataString = [JsonUtil convertDictionaryToJson:[[NSDictionary alloc]initWithObjectsAndKeys:uid, @"uid",class_code,@"classcode",
                                                              @(1),@"utype",[[UserDao getInstance]getAccessToken],@"token",@(baby.cid),@"childid",@(1),@"checkname",nil]];
    
    
    PopUIManager *popUIMgr = [PopUIManager getInstanse];
    [popUIMgr showWaitingUI:self.view];
    
    [[NetWorkManager getInstanse] requestURLAsynMessage:BABY_JOIN_CLASS data:dataString FinishBlock:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
        if (connectionError) { //连接失败
            debugLog(@"Http Error: %@   %ld", connectionError.localizedDescription,(long)connectionError.code);
            NSString *error_content = [NSString stringWithFormat:@"连接错误:%ld",(long)connectionError.code];
            [popUIMgr popAlertView:nil title:@"提示" message:error_content cancelButtonTitle:@"确定"];
        }else{//连接成功，判断是否有数据返回
            NSInteger responseCode = [(NSHTTPURLResponse *)response statusCode];
            NSLog(@"服务器返回StateCode:%ld", (long)responseCode);
            
            if (data) {
                NSDictionary *dict = [JsonUtil convertDataToDictionary:data];
                NSLog(@"数据字典: %@", dict);
                
                if ([[dict objectForKey:@"ret"] integerValue]== 1) {
                    //登录失败，弹窗提示
                    NSString *ret_msg;
                    switch ([[dict objectForKey:@"retCode"] integerValue]) {
                        case 1:{
                            ret_msg= @"SuccessJoin";
                            //加入班级成功~
                            NSDictionary *classinfo = [dict objectForKey:@"classinfo"];
                            NSString *fid = [dict objectForKey:@"fid"];
                            if(fid!=nil &&  fid!=[NSNull null]){
                                NSDictionary *update_user = @{@"fid":fid,@"fcode":[dict objectForKey:@"invite_code"]};
                                [[UserDao getInstance]updateUserInfo:update_user withReload:YES];
                            }
                            NSMutableDictionary *updateDict = [[NSMutableDictionary alloc]init];
                            [updateDict setObject:@([[classinfo objectForKey:@"id"] integerValue]) forKey:@"classid"];
                            [updateDict setObject:[classinfo objectForKey:@"name"] forKey:@"classname"];
                            [updateDict setObject:[classinfo objectForKey:@"schoolid"] forKey:@"schoolid"];
                            [updateDict setObject:[classinfo objectForKey:@"schoolname"] forKey:@"schoolname"];
                            [updateDict setObject:[classinfo objectForKey:@"kx_auth"] forKey:@"kx_auth"];
                            [[BabyDao getInstance]updateBabyInfo:updateDict withCid:baby.cid];
                            
                            //更新数据
                            if(_babyid>0){
                                 [[BabyDao getInstance]setCurrentBaby:baby];
                                 ((AppDelegate*)[UIApplication sharedApplication].delegate).dyn_need_refresh = YES;
                                [self.navigationController popToRootViewControllerAnimated:YES];
                                
                            }else{
                                [self goInMain];
                            }
                            break;
                        }
                        case 10016:
                        {
                            ret_msg= @"SuccessJoin";
                            NSArray *others = [dict objectForKey:@"others"];
                            NSString *avatar_head = [dict objectForKey:@"avatar_header"];
                            MultiBabyViewController *multi = [[MultiBabyViewController alloc]init];
                            multi.babyName = baby.cname;
                            multi.babyId = baby.cid;
                            multi.classCode = class_code;
                            [multi setModalPresentationStyle:UIModalPresentationCurrentContext];
                            multi.avatar_header = avatar_head;
                            multi.childArr = others;
                            if(_babyid>0){
                                multi.add_baby = YES;
                            }
                            //[self.navigationController presentViewController:multi animated:YES completion:^{
                                
                           // }];
                            
                            UIWindow *window = [[UIApplication sharedApplication]keyWindow];
                            multi.view.frame = window.bounds;
                            [multi showInView:window animated:YES];
                            [self addChildViewController:multi];
                            [multi didMoveToParentViewController:self];
                            
                            break;
                        }
                        case 2:{
                            ret_msg= @"宝贝信息不存在";
                            break;
                        }case 3:{
                            ret_msg= @"宝贝已经加入了班级,不能重复加入";
                            break;
                        }case 4:{
                            ret_msg= @"班级码不存在";
                            break;
                        }default:{
                            ret_msg= @"未知错误";
                            break;
                        }
                    }
                    if (![ret_msg isEqual:@"SuccessJoin"]) {
                        [popUIMgr popAlertView:nil title:@"提示" message:ret_msg cancelButtonTitle:@"确定"];
                    }
                }else{
                    [popUIMgr popAlertView:nil title:@"提示" message:@"数据解析错误" cancelButtonTitle:@"确定"];
                }
            }else{
                [popUIMgr popAlertView:nil title:@"提示" message:@"服务器没有返回数据" cancelButtonTitle:@"确定"];
            }
        }
        [popUIMgr removeWaitingUI];
    }];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
}



@end
